package com.sevlet;

import com.Bean.Employee;
import com.Bean.VoBean.SocialUser;
import com.dao.EmployeeDao;
import com.dao.impl.EmployeeDaoimpl;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.util.HttpUtils;
import com.util.JWTTokenUtil;
import com.util.JsonUtil;
import com.util.ProxyUtil;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@WebServlet("/oauth2.0/weibo/success")

public class WeiBoServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String code = req.getParameter("code");
        System.out.println(code);

        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson gson = gsonBuilder.create();

        JsonUtil jsonUtil = new JsonUtil();
        // 根据code换取 Access Token
        Map<String,String> map = new HashMap<>();
        map.put("client_id", "3616761735");
        map.put("client_secret", "88a0275cf46d6d9af01b49967f745552");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://localhost:9090/MyWeb2/oauth2.0/weibo/success");
        map.put("code", code);
        Map<String, String> headers = new HashMap<>();
        //1.根据code换取accessToken
//        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", headers, null, map);
        HttpResponse response = null;
        try {
            response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", headers, null, map);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //2.处理
        if (response.getStatusLine().getStatusCode()==200) {
            //获取到了accessToken
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = gson.fromJson(json, SocialUser.class);

            EmployeeDao employeeDao =(EmployeeDao) ProxyUtil.getDaoProxy(new EmployeeDaoimpl());

            try {
                Employee employee = employeeDao.queryDataByUid(socialUser);
                if (employee!=null){//这个社交用户已经注册过，关联到员工表
                    //修改员工表数据
                    Employee updateEmployee = new Employee();
                    updateEmployee.setEid(employee.getEid());
                    updateEmployee.setAccess_token(socialUser.getAccess_token());
                    updateEmployee.setExpires_in(socialUser.getExpires_in());
                    int i = employeeDao.updateDataByid(updateEmployee);
                    if (i>0){
                        System.out.println("修改成功");
                    }

                    //{"eid":"d383d12f-0134-43ae-b1bd-f8ff69271ef2","name":"小二丶孟婆糖灬","social_uid":"7326397176","access_token":"2.005aoozHhwYlwD771fae464bYnDUyB","expires_in":"157679999"}
                    employee.setAccess_token(socialUser.getAccess_token());
                   employee.setExpires_in(socialUser.getExpires_in());

                    JWTTokenUtil jwtTokenUtil = new JWTTokenUtil();
                    String encodeToken = jwtTokenUtil.getEncodeToken(gson.toJson(employee));
                    jsonUtil.setCode(0);
                   jsonUtil.setMsg(encodeToken);
                   jsonUtil.setData(gson.toJson(employee.getName()));
                  //  session.setAttribute("userinfo",jsonUtil);

                    resp.sendRedirect("http://localhost:8080/#/weibo?json="+ URLEncoder.encode(gson.toJson(jsonUtil),"utf-8") );
                  return;

                }else {
                    //该用户需要注册
                    //
                     Employee registeEmployee = new Employee();
                        HashMap<String, String> hashMap = new HashMap<>();
                        map.put("access_token", socialUser.getAccess_token());
                        map.put("uid", socialUser.getUid());
                        HttpResponse userInfo = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), map);
                        if (userInfo.getStatusLine().getStatusCode()==200) {
                            //获取到了用户信息
                            String json1 = EntityUtils.toString(userInfo.getEntity());
                            Employee employee1 = gson.fromJson(json1, Employee.class);
                            registeEmployee.setName(employee1.getName());
                        }

                   registeEmployee.setEid(UUID.randomUUID().toString());
                    registeEmployee.setSocial_uid(socialUser.getUid());
                    registeEmployee.setExpires_in(socialUser.getExpires_in());
                    registeEmployee.setAccess_token(socialUser.getAccess_token());
                    int s = employeeDao.insertSocialUser(registeEmployee);
                    if(s>0){
                        System.out.println("插入成功");
                    }
                    System.out.println(registeEmployee);
                    JWTTokenUtil jwtTokenUtil = new JWTTokenUtil();
                    String encodeToken = jwtTokenUtil.getEncodeToken(gson.toJson(registeEmployee));
                    jsonUtil.setCode(0);
                    jsonUtil.setMsg(encodeToken);
                    jsonUtil.setData(gson.toJson(registeEmployee.getName()));
                    resp.sendRedirect("http://localhost:8080/#/weibo?json="+ URLEncoder.encode(gson.toJson(jsonUtil),"utf-8") );
                    return;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

}
 
 
 

